package com.hailiao.beidou.message.data.db.dao

import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.hailiao.beidou.message.data.db.DB
import com.hailiao.beidou.message.data.db.entity.ChatEntity
import com.hailiao.beidou.message.data.db.entity.ChatWithContactEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface ChatDao {

    // 分页查询
    @Transaction
    @Query("SELECT * FROM chat_table ORDER BY `time` DESC")
    fun pagingSource(): PagingSource<Int, ChatWithContactEntity>

    // 模糊查询
    @Transaction
    @Query("SELECT * FROM chat_table WHERE number LIKE '%'||:value||'%' ORDER BY `time` DESC")
    suspend fun susQueryLike(value: String): List<ChatWithContactEntity>

    // 查询
    @Query("SELECT * FROM chat_table WHERE number = :number")
    suspend fun susQuery(number: String): ChatEntity?

    // 查询
    @Transaction
    @Query("SELECT * FROM chat_table WHERE number = :number")
    fun queryWithContact(number: String): Flow<ChatWithContactEntity?>

    // 查询草稿信息
    @Query("SELECT draftContent FROM chat_table WHERE number = :number")
    suspend fun susQueryDraft(number: String): String?

    // 更新草稿信息
    @Query("UPDATE chat_table SET draftContent = :draft WHERE number = :number")
    suspend fun susUpdateDraft(number: String, draft: String)

    // 清除未读数
    @Query("UPDATE chat_table SET unreadCount = 0 WHERE number = :number")
    suspend fun susClearUnreadCount(number: String)

    // 插入
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(info: ChatEntity): Long

    // 修改
    @Update(onConflict = OnConflictStrategy.REPLACE)
    suspend fun update(info: ChatEntity)

    // 删除
    @Delete
    suspend fun delete(info: ChatEntity)

    // 删除
    @Query("DELETE FROM chat_table WHERE number = :number")
    suspend fun delete(number: String)

    // 删除
    @Transaction
    suspend fun deleteWithMessage(info: ChatEntity) {
        delete(info)
        DB.instant.messageDao().delete(info.number)
    }
}